package dev.entao.travel

import dev.entao.core.Action
import dev.entao.core.HttpApis
import dev.entao.core.HttpContext
import dev.entao.core.render.sendResult
import dev.entao.core.slices.SessionSlice
import dev.entao.core.slices.TokenSlice
import dev.entao.sql.EQ
import dev.entao.travel.model.Account
import dev.entao.travel.model.User
import dev.entao.travel.model.jsonData

class AuthApi(context: HttpContext) : HttpApis(context) {
    @Action
    fun loginAccount(phone: String, pwd: String) {

        val ac = Account.one(Account::phone EQ phone, Account::pwd EQ pwd, Account::status EQ Account.ST_ENABLE)
        if (ac != null) {
            SessionSlice.putAccountId(context, ac.id, AppConst.ACCOUNT)
            val token = TokenSlice.makeToken(ac.id, TYPE_ADMIN, 0)
            context.sendResult {
                put("token", token)
            }
        } else {
            context.sendResult {
                failed("用户名或密码错误")
            }
        }
    }

    @Suppress("UNUSED_PARAMETER")
    @Action
    fun loginUser(uuid: String, phone: String, pwd: String) {
        val u = User.one(User::phone EQ phone, User::pwd EQ pwd, User::status EQ 0) ?: return context.sendResult {
            failed("用户名或密码错误")
        }
        val token = TokenSlice.makeToken(u.id, TYPE_USER, 0)
        context.sendResult {
            put("token", token)
            data(u.jsonData().apply {
                "token" TO token
            })
        }
    }

    companion object {
        const val TYPE_ADMIN = "admin"
        const val TYPE_USER = "user"
    }
}